<template>
  <view class="container">
    <form @submit="formSubmit" @reset="formReset">

      <!-- 单位选择 -->
      <view class="form-item">
        <view class="form-row">
          <text class="label">单位</text>

          <picker @change="getUnits" :value="unitIndex" :range="units">
            <view class="form-unit">
              <view class="picker-text">{{units[unitIndex] || '请选择'}}</view>
              <img class="return" src="../../static/return.png" alt="" />
            </view>
          </picker>

        </view>
      </view>

      <!-- 位置选择 -->
      <view class="form-item">
        <view class="form-row">
          <text class="label">位置</text>
          <view class="picker" @click="goToSelector('location', '位置')">
            <view class="picker-text">{{formData.location || '请选择'}}</view>
            <img class="return" src="../../static/return.png" alt="" />
          </view>
        </view>
      </view>

      <!-- 对象选择 -->
      <view class="form-item">
        <view class="form-row">
          <text class="label">对象</text>
          <view class="picker" @click="goToSelector('repairObject', '对象')">
            <view class="picker-text">{{formData.repairObject || '请选择'}}</view>
            <img class="return" src="../../static/return.png" alt="" />
          </view>
        </view>
      </view>


      <!-- 描述输入 -->
      <view class="form-item-description">
        <view class="form-row-description">
          <text class="label">描述</text>
          <view class="textarea-container">
            <input class="input" v-model="formData.description" placeholder="请输入描述" maxlength="1024"
              @input="countChars" />
            <text class="char-count">{{charCount}}/1024</text>
          </view>
        </view>
      </view>

      <!-- 图片/视频上传 -->
      <view class="form-item">
        <view class="form-row">
          <text class="label">图片/视频</text>
          <view class="upload-content">

            <view class="upload-btn" @click="chooseMedia"> <text>请上传真实图片/视频</text>
              <uni-icons type="plusempty" size="30" color="#999"></uni-icons>
            </view>
            <view class="preview-list">
              <view class="preview-item" v-for="(item, index) in mediaList" :key="index">
                <image v-if="item.type === 'image'" :src="item.path" class="preview-image" mode="aspectFill"></image>
                <video v-else :src="item.path" class="preview-video"></video>
                <view class="delete-btn" @click="deleteMedia(index)">
                  <uni-icons type="closeempty" size="20" color="#fff"></uni-icons>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 姓名输入 -->
      <view class="form-item">
        <view class="form-row">
          <text class="label">姓名</text>
          <input class="input" v-model="formData.reporterName" placeholder="请输入您的姓名" />
        </view>
      </view>

      <!-- 手机号输入 -->
      <view class="form-item-nobody">
        <view class="form-row ">
          <text class="label">手机号</text>
          <input class="input" v-model="formData.reporterPhone" placeholder="请输入11位手机号" type="number" maxlength="11" />
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="btn-group">
        <button form-type="submit" class="submit-btn">提交</button>
      </view>
    </form>
  </view>
</template>

<script>
  import {
    ajax
  } from '../../utils/request.js';
  export default {
    data() {
      return {
        formData: {
          reporterName: '',
          reporterPhone: '',
          unit: '',
          location: '',
          repairObject: '',
          description: '',
          source: '微信',
          locationId: '',
          repairObjectId: ''
        },
        charCount: 0,
        mediaList: [],
        currentField: '',
        // Add unit related data
        units: [],
        unitIndex: 0
      }
    },

    onShow() {
      // 获取单位列表
      this.getUnits();


    },
    methods: {
      getUnits() {
        const userInfo = uni.getStorageSync('userInfo');
        this.name = userInfo.name || '';
        this.phone = userInfo.phone || '';
        this.formData.reporterName = userInfo.name || '';
        this.formData.reporterPhone = userInfo.phone || '';
        // 获取单位列表
        ajax('/api/dixiu/getunit', 'POST')
          .then(res => {

            if (res.success && res.data && res.data.unit) {

              this.units = res.data.unit.map(item => item.name);

              if (this.units.length > 0) {
                this.unitIndex = 0;
                this.formData.unit = this.units[0];
              }
            }
          })
          .catch(err => {
            console.error('获取单位列表失败:', err);
            uni.showToast({
              title: '获取单位失败',
              icon: 'none'
            });
          });
      },
      // 选择媒体文件
      chooseMedia() {
        uni.chooseMedia({
          count: 9,
          mediaType: ['image', 'video'],
          sourceType: ['album', 'camera'],
          maxDuration: 30,
          camera: 'back',
          success: (res) => {
            res.tempFiles.forEach(file => {
              this.mediaList.push({
                path: file.tempFilePath,
                type: file.fileType,
                size: file.size
              })
            })
          }
        })
      },
      // 跳转到选择器页面
      goToSelector(field, title) {
        this.currentField = field;
        uni.navigateTo({
          url: `/life/chose/chose?title=${title}`,
          events: {
            // 接收选择器页面返回的数据
            acceptDataFromSelector: (data) => {
              console.log(data);
              this.formData[this.currentField] = data.name;
              if (this.currentField === 'location') {
                this.formData.locationId = data.id;
              } else if (this.currentField === 'repairObject') {
                this.formData.repairObjectId = data.id;
              }
            }
          },
          success: (res) => {
            // 页面打开成功，设置当前选择的字段
            res.eventChannel.emit('setField', {
              field: field
            });
          }
        });
      },

      // 字符计数
      countChars() {
        // 去除所有空格后计算字符数
        this.charCount = this.formData.description ? this.formData.description.replace(/\s/g, '').length :
          0;
      },

      // 上传媒体文件
      async uploadMediaFiles() {
        const uploadedUrls = [];
        const token = uni.getStorageSync('token');

        // 逐个上传媒体文件
        for (const media of this.mediaList) {
          try {
            const res = await uni.uploadFile({
              url: 'https://api.flowergk.com/api/dixiu/upload',
              filePath: media.path,
              name: 'signatureImage',
              header: {
                'Authorization': token
              }
            });

            const data = JSON.parse(res[1].data);
            if (data.success && data.data.signatureImage) {
              uploadedUrls.push(data.data.signatureImage);
            }
          } catch (error) {
            console.error('上传文件失败:', error);
            throw error;
          }
        }

        return uploadedUrls;
      },

      // 删除媒体文件
      deleteMedia(index) {
        this.mediaList.splice(index, 1)
      },

      // 表单提交
      async formSubmit(e) {
        // 验证表单
        if (!this.formData.reporterName) {
          uni.showToast({
            title: '请输入姓名',
            icon: 'none'
          })
          return
        }

        if (!this.formData.reporterPhone || !/^1[3-9]\d{9}$/.test(this.formData.reporterPhone)) {
          uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none'
          })
          return
        }

        if (!this.formData.unit) {
          uni.showToast({
            title: '请选择单位',
            icon: 'none'
          })
          return
        }

        if (!this.formData.location) {
          uni.showToast({
            title: '请选择位置',
            icon: 'none'
          })
          return
        }

        if (!this.formData.repairObject) {
          uni.showToast({
            title: '请选择对象',
            icon: 'none'
          })
          return
        }

        // 显示提交成功
        uni.showLoading({
          title: '提交中...'
        })
        try {


          // 1. 先上传图片
          let signatureImage = [];
          if (this.mediaList.length > 0) {
            signatureImage = await this.uploadMediaFiles();
          }

          // 2. 提交表单数据
          const data = {

            ...this.formData,
            image: signatureImage
          };

          await ajax(
            '/api/dixiu/addworkorder',
            'POST',
            data
          );

          uni.hideLoading();
          uni.showToast({
            title: '提交成功'
          })
          setTimeout(() => {
            this.formReset()
          }, 1000);

        } catch (error) {
          uni.hideLoading();
          uni.showToast({
            title: '提交失败',
            icon: 'none'
          });
          console.error('提交失败:', error);
        }

      },

      // 表单重置
      formReset() {
        this.formData = {
          reporterName: '',
          reporterPhone: '',
          unit: '',
          location: '',
          repairObject: '',
          description: ''
        }
        this.charCount = 0
        this.mediaList = []
      }
    }
  }
</script>

<style>
  .container {
    padding: 20px;
    background-color: #f5f5f5;
    height: 100vh;

  }

  .container form {
    height: 100vh;
    position: fixed;
    width: 90vw;
  }

  .form-item {
    background-color: #fff;
    padding: 5px 10px;
    /* box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05); */
  }


  form .form-item-nobody {
    background-color: #fff;
    padding: 10px 5px 0px 10px;
  }



  .form-row {
    border-bottom: #e3e3e3 0.1px solid;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;

  }

  .form-unit {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }



  .form-item-description {
    padding: 10px 10px;
    background-color: #fff;
  }

  .form-row-description {
    border-bottom: #e3e3e3 0.1px solid;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 80px;
    line-height: 80px;
  }



  .label {
    height: 40px;
    line-height: 40px;
    font-size: 16px;
    color: #333;
    width: 80px;
    flex-shrink: 0;
    padding-left: 10px;
  }

  .return {
    width: 15px;
    height: 15px;
    transform: rotate(180deg);
    margin-left: 5px;
  }

  .input {
    flex: 1;
    height: 40px;
    border: none;
    padding: 0 10px;
    border-radius: 4px;
    font-size: 14px;
  }

  .picker {
    display: flex;
    align-items: center;
    jsustify-content: space-between;

    height: 40px;
    line-height: 40px;
  }

  .picker-icon {
    width: 15px;
    height: 15px;
  }

  .picker-text {
    color: #666;
  }

  .textarea-container {
    height: 40px;
    line-height: 40px;
  }



  .textarea-container {
    flex: 1;
    position: relative;
    height: auto;
    height: 40px;
  }

  .textarea-container .input {
    height: 40px;
    padding: 0 10px;
    font-size: 16px;
    width: 100%;
    box-sizing: border-box;
    outline: none;

  }

  .char-count {
    position: absolute;
    bottom: -80%;
    right: 10px;
    font-size: 12px;
    color: #999;
  }

  .upload-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    color: #999;
  }

  .upload-btn {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;


    color: #999;

  }

  .preview-list {
    display: flex;
    flex-wrap: wrap;
    margin-top: 5px;
  }

  .preview-item {
    position: relative;
    width: 80px;
    height: 80px;
    margin-right: 10px;
    margin-bottom: 10px;
  }

  .preview-image,
  .preview-video {
    width: 100%;
    height: 100%;
    border-radius: 4px;
  }

  .delete-btn {
    position: absolute;
    top: -8px;
    right: -8px;
    width: 20px;
    height: 20px;
    background-color: #f56c6c;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .btn-group {
    margin-top: 30px;
    background-color: #2BA245;
  }

  .submit-btn {
    width: 80%;
    height: 45px;
    line-height: 45px;
    border-radius: 22.5px;
    font-size: 16px;
    background-color: #2BA245;
    color: #fff;
  }
</style>